package _15_generics._15_2.exercise;

/**
 *
 */
public class E04_GenericSequence {
    public static void main(String[] args) {
        Sequence<String> sequence = new Sequence<String>(10);
        sequence.add("hello");
        sequence.add("world");
        Selector<String> selector = sequence.selector();
        while (!selector.end()){
            System.out.println(selector.current());
            selector.next();
        }
    }
}

interface Selector<T> {
    boolean end();
    T current();
    void next();
}

class Sequence<T> {
    private Object[] items;
    private int index;

    public Sequence(int size){
        items = new Object[size];
    }

    public void add(T x){
        if (index < items.length){
            items[index++] = x;
        }
    }
    public Selector<T> selector(){
        return new SequenceSelector();
    }

    private class SequenceSelector implements Selector<T> {
        private int i;
        public boolean end() {
            return i == items.length;
        }

        public T current() {
            return (T) items[i];
        }

        public void next() {
            if (i < items.length){
                i++;
            }
        }
    }
}
